package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.filter.WmTokenFilter;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.plugin2.message.SetChildWindowHandleMessage;

import java.io.FileInputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author lo
 * @date 2021/9/22
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    /**
     * 上传图片功能
     *
     * @param multipartFile
     * @return
     */
    @Autowired
    FileStorageService fileStorageService;
    //前缀
    @Value("${file.oss.prefix}")
    String prefix;
    //访问前缀
    @Value("${file.oss.web-site}")
    String site;

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文件不存在");
        }

        //2.获取线程中的id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH, "请登录后再操作");
        }

        String store = null;
        //获取文件名
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            //后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //3.向oss上传文件
            String name = multipartFile.getName();
            // 为避免文件名重复,使用UUID+后缀的方式
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //返回图片路径
            store = fileStorageService.store(prefix, uuid + substring, multipartFile.getInputStream());
            // 访问地址= 访问前缀+图片路径
            String url = site + "/" + store;
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器异常,文件上传失败");
        }

        //向数据库增加一条素材数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        // oss路径
        wmMaterial.setUrl(store);
        wmMaterial.setType((short) 0);
        //0 未收藏 ,1 收藏
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());

        //保存结果
        save(wmMaterial);
        //返回结果
        //访问路径
        wmMaterial.setUrl(site + wmMaterial.getUrl());
        System.out.println(wmMaterial.getUrl());

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 图片显示
     *
     * @param wmMaterialDTO
     * @return
     */
    @Override
    public ResponseResult getList(WmMaterialDTO wmMaterialDTO) {
        //1.参数校验
        wmMaterialDTO.checkParam();
        //根据id查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "用户没有登录");
        }
        //2.查询数据
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        //根据用户id查询, 并且根据创建时间倒序,排序
        wrapper.eq(WmMaterial::getUserId, user.getId()).orderByDesc(WmMaterial::getCreatedTime);
        if (wmMaterialDTO.getIsCollection() != null && wmMaterialDTO.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, wmMaterialDTO.getIsCollection());
        }
        Page<WmMaterial> page = new Page<>(wmMaterialDTO.getPage(), wmMaterialDTO.getSize());

        this.page(page, wrapper);
        for (WmMaterial record : page.getRecords()) {
            record.setUrl(site + record.getUrl());
        }

        //封装参数并返回
        PageResponseResult result = new PageResponseResult(wmMaterialDTO.getPage(), wmMaterialDTO.getSize(), page.getTotal(), page.getRecords());
        return result;
    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.查询图片信息
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            //说明没有这张图片
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3. 根据wmMaterial的id查询引用表的数据
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getId, wmMaterial.getId());

        Integer count = wmNewsMaterialMapper.selectCount(wrapper);

        if (count > 0) {
            //说明正在被引用
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "图片正在被引用");
        }

        //4.删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1. 校验数据
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.更新状态
        Integer userId = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, userId)
                .set(WmMaterial::getIsCollection, type)
        );
        return ResponseResult.okResult();
    }
}
